<script setup lang="ts">
import VChart from 'vue-echarts'
import 'echarts'
import { computed, onMounted, ref } from 'vue'
import { getWaterContentData } from '@/api/environmentalDataController.ts'
import { useEnvironmentDataStore } from '@/stores/useEnvironmentDataStore.ts'

// 初始化为空数组而非undefined，避免展开运算符错误
const dateList = ref<string[]>([])
const valueList = ref<number[]>([])
const environmentDataStore = useEnvironmentDataStore()

const fetchWaterContentData = async () => {
  try {
    const res = await getWaterContentData()
    // 安全赋值，确保始终是数组类型
    dateList.value = res.data.data?.dataTimestampList || []
    valueList.value = res.data.data?.waterContentList || []
    environmentDataStore.setMoisture(valueList.value)
  } catch (err) {
    // 出错时保持空数组，避免图表报错
    dateList.value = []
    valueList.value = []
  }
}

onMounted(() => {
  fetchWaterContentData()
})

const options = computed(() => {
  // 处理空数组情况，避免Math.max报错
  const maxValue = valueList.value.length ? Math.max(...valueList.value) * 1.2 : 100 // 空数据时使用默认最大值

  // 保持你原来的渐变配置
  const colorGradient = {
    type: 'linear',
    x: 0,
    y: 0,
    x2: 0,
    y2: 1,
    colorStops: [
      { offset: 0, color: '#1E3A8A' },
      { offset: 1, color: '#87CEFA' },
    ],
  }

  return {
    visualMap: [
      {
        show: false,
        type: 'continuous',
        seriesIndex: 0,
        min: 0,
        max: maxValue, // 使用安全计算的最大值
      },
    ],
    title: {
      left: 'center',
      text: '含水量分析',
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const { name, value } = params[0]
        return `时间：${name}<br>含水量：${value}%`
      },
    },
    xAxis: {
      data: dateList.value,
      name: '时间',
    },
    yAxis: {
      name: '含水量（%）',
      min: 0,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true,
    },
    series: [
      {
        type: 'line',
        showSymbol: true,
        symbol: 'circle',
        symbolSize: 6,
        smooth: true,
        data: valueList.value,
        lineStyle: {
          width: 3,
          color: colorGradient,
        },
        areaStyle: {
          color: {
            ...colorGradient,
            colorStops: [
              { offset: 0, color: 'rgba(30, 58, 138, 0.6)' },
              { offset: 1, color: 'rgba(135, 206, 250, 0.2)' },
            ],
          },
        },
        markPoint: {
          data: [
            { type: 'max', name: '最高含水量' },
            { type: 'min', name: '最低含水量' },
          ],
        },
      },
    ],
  }
})
</script>

<template>
  <div class="data-water-content-analyze">
    <a-card title="含水量分析">
      <v-chart :option="options" style="height: 60vh; max-width: 100%" />
    </a-card>
  </div>
</template>

<style scoped></style>
